package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.PageParam;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper mapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetMealService setMealService;

    //新增分类
    @Override
    public int add(Category category) {

        return mapper.insert(category);
    }

    //分页查询
    @Override
    public IPage<Category> findPage(PageParam pageParam) {

        //定义要查询的页码，每页查询的条数
        IPage<Category> page = new Page<>(pageParam.getPage(), pageParam.getPageSize());

        return mapper.selectPage(page, null);
    }

    //删除分类
    @Override
    public int delete(long categoryId) {

        int count = dishService.findCountByCategoryId(categoryId);

        if (count > 0) {//有关联数据
            throw new CustomException("该分类存在菜品数据，无法删除！");
        }


        count = setMealService.findCountByCategoryId(categoryId);

        if (count > 0) {
            throw new CustomException("该分类存在套餐数据，无法删除！");

        }

        return mapper.deleteById(categoryId);
    }

    //修改分类
    @Override
    public int update(Category category) {

        return mapper.updateById(category);

    }

    /**
     * 根据类型查询分类数据
     *
     * @param type
     * @return
     */
    @Override
    public List<Category> findCategoryByType(Integer type) {

        //创建查询条件
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(type != null, Category::getType, type);

        //添加排序
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        return mapper.selectList(lqw);
    }

    @Override
    public Category findById(long id) {
        return mapper.selectById(id);
    }
}
